package com.dealer.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dealer.management.common.Result;
import com.dealer.management.entity.User;
import com.dealer.management.mapper.UserMapper;
import com.dealer.management.service.UserService;
import com.dealer.management.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Result login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("status", 1);
        queryWrapper.eq("deleted", 0);
        
        User user = userMapper.selectOne(queryWrapper);
        
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return Result.error("密码错误");
        }
        
        String token = jwtUtils.generateToken(user.getId().toString());
        
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("token", token);
        
        // 移除密码
        user.setPassword(null);
        
        return Result.success("登录成功", result);
    }

    @Override
    public Result getCurrentUserInfo() {
        // 这里应该从SecurityContext中获取当前用户ID
        // 暂时返回空
        return Result.success();
    }
}
